import axios from 'axios'
import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter'
import { httpLogError, requestError, throttleToLogin } from './utils'

export function createService() {
	const request = axios.create({ adapter: createUniAppAxiosAdapter() })
	request.interceptors.request.use(
		(request) => {
			return request
		},
		(err) => {
			return Promise.reject(err)
		}
	)

	request.interceptors.response.use(
		(response) => {
			const dataAxios = response.data
			// 这个状态码是和后端约定的
			const { code, data, msg } = dataAxios
			// 根据 code 进行判断
			if (code === undefined) {
				return dataAxios
			} else {
				switch (`${code}`) {
					case '0': // code === 0代表没有错误
						return dataAxios
					case '401001': // code === 401001 代表token 过期打回登录页
						throttleToLogin()
						return dataAxios
					case '45000': // code === 45000 代表token 过期打回登录页
						throttleToLogin()
						return dataAxios
					case '500002': // code === 500002 代表接口报错
						httpLogError(new Error(msg))
						break
					default: // 不是正确的 code
						requestError(response)
						return dataAxios
				}
			}
		},
		(error) => {
			const status = error.response?.status
			switch (status) {
				// TODO 再考虑下怎么判断是跨域问题
				case undefined:
				case null:
					httpLogError(error)
					break
				case 400:
					httpLogError(error)
					break
				case 401:
					httpLogError(error)
					break
				case 403:
					httpLogError(error)
					break
				case 404:
					httpLogError(error)
					break
				case 408:
					httpLogError(error)
					break
				case 500:
					httpLogError(error)
					break
				case 501:
					httpLogError(error)
					break
				case 502:
					httpLogError(error)
					break
				case 503:
					httpLogError(error)
					break
				case 504:
					httpLogError(error)
					break
				case 505:
					httpLogError(error)
					break
				default:
					httpLogError(error)
					break
			}
			return Promise.reject(error)
		}
	)
	return request
}

export const service = createService()